﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Automation;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.IO;
using NicoView.Model.Share.MediaEncoders;

namespace NiconicoLiveEncoder
{
    public class NiconicoLiveEncoderConroller:BroadcastMediaEncoderBase
    {


        internal const string NiconicoLiveEncoderProgramName = "Nicoliveenc";

        internal const string VHMultiWriterExt2NameProgramName = "VHMultiWriterExt2";

        private static string niconicoLiveEncoderPath = null;

        public static string NiconicoLiveEncoderPath
        {
            get
            {
                if (niconicoLiveEncoderPath == null)
                {
                    var programFilesFolder = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
                    niconicoLiveEncoderPath = programFilesFolder + @"\niwango\nicoliveenc\" + NiconicoLiveEncoderProgramName + ".exe";

                }

                return niconicoLiveEncoderPath;
            }
        }


        public static bool NiconicoLiveEncoderInsalled
        {
            get
            {
                return File.Exists(NiconicoLiveEncoderPath);
            }
        }

       

        public NiconicoLiveEncoderConroller(IBroadcastMediaEncoderProvider provider)
            : base(provider)
        {


        }
        

        public override async void StartEncode(BroadcastMediaEncodeStartInfo startInfo)
        {
            if (!IsEncoding)
            {
                var nleProcess = await getNiconicoLiveEncoderProcessAsync();

                if (nleProcess != null)
                {
                    var automationElement = AutomationElement.FromHandle(nleProcess.MainWindowHandle);

                    clickStartButton(automationElement);
                }
            }
            
        }

        private void clickStartButton(AutomationElement automationElement)
        {
            if (automationElement != null)
            {
                var startButton = automationElement.FindFirst(TreeScope.Element | TreeScope.Descendants, new PropertyCondition(
                                                    AutomationElement.NameProperty,
                                                    "スタート"));

                if (startButton != null)
                {
                    var startButtonPattern = (InvokePattern)startButton.GetCurrentPattern(InvokePattern.Pattern);


                    startButtonPattern.Invoke();
                }
                
            }
        }

        private async Task<Process> getNiconicoLiveEncoderProcessAsync()
        {
            var processes = getNiconicoLiveEncoderProcesses();

            if (processes.Length <= 0)
            {
                if (NiconicoLiveEncoderInsalled)
                {
                    return await Task<Process>.Run(() =>
                    {
                        var process = Process.Start(NiconicoLiveEncoderPath);
                        process.WaitForExit(5000);
                        return process;
                    });

                    
                }

                else
                {
                    return null;
                }
                
            } 
            else
            {
                return processes.First();
            }

        }

        private Process[] getNiconicoLiveEncoderProcesses()
        {
            return Process.GetProcessesByName(NiconicoLiveEncoderProgramName);
        }

        public override void Dispose()
        {
            StopEncode();
        }

        public override async void StopEncode()
        {
            var processes = getNiconicoLiveEncoderProcesses();

            foreach (var process in processes)
            {
                if (IsEncoding)
                {
                    var automationElement = AutomationElement.FromHandle(process.MainWindowHandle);
                    clickStartButton(automationElement);
                    await Task.Delay(TimeSpan.FromSeconds(5));
                }
                
            }
        }

        public override bool IsEncoding
        {
            get { return Process.GetProcessesByName(VHMultiWriterExt2NameProgramName).Any(); }
        }
    }
}
